from sqlalchemy import Column, Integer, String, DateTime, Text, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from database import Base

class User(Base):
    __tablename__ = "users"
    
    id = Column(Integer, primary_key=True, index=True)
    username = Column(String(50), unique=True, index=True, nullable=False)
    email = Column(String(100), unique=True, index=True, nullable=False)
    hashed_password = Column(String(255), nullable=False)
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    updated_at = Column(DateTime(timezone=True), onupdate=func.now())
    
    # 关系
    fortune_records = relationship("FortuneRecord", back_populates="user")

class FortuneRecord(Base):
    __tablename__ = "fortune_records"
    
    id = Column(Integer, primary_key=True, index=True)
    user_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    
    # 用户信息
    name = Column(String(50), nullable=True)  # 姓名
    gender = Column(String(10), nullable=True)  # 性别：男/女
    
    # 生辰信息（北京时间）
    birth_year = Column(Integer, nullable=False)
    birth_month = Column(Integer, nullable=False)
    birth_day = Column(Integer, nullable=False)
    birth_hour = Column(Integer, nullable=False)
    birth_minute = Column(Integer, nullable=False)
    longitude = Column(String(20), nullable=True)  # 经度（用于真太阳时计算，存储为字符串）
    province = Column(String(50), nullable=True)  # 省份
    city = Column(String(50), nullable=True)  # 城市
    
    # 真太阳时信息
    solar_year = Column(Integer, nullable=True)
    solar_month = Column(Integer, nullable=True)
    solar_day = Column(Integer, nullable=True)
    solar_hour = Column(Integer, nullable=True)
    solar_minute = Column(Integer, nullable=True)
    
    # 八字信息
    year_pillar = Column(String(10), nullable=False)  # 年柱
    month_pillar = Column(String(10), nullable=False)  # 月柱
    day_pillar = Column(String(10), nullable=False)   # 日柱
    hour_pillar = Column(String(10), nullable=False)  # 时柱
    
    # AI 分析结果
    ai_analysis = Column(Text, nullable=True)  # 第二阶段的详细分析
    
    # 阶段标识
    stage = Column(Integer, default=1)  # 1: 仅计算八字, 2: 已进行AI分析
    
    # 时间戳
    created_at = Column(DateTime(timezone=True), server_default=func.now())
    
    # 关系
    user = relationship("User", back_populates="fortune_records")
